package cn.net.wanji.service.iml;

import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.entity.JsonRoot;
import cn.net.wanji.entity.deviceInfo.DeviceInfo;
import cn.net.wanji.entity.deviceStatus.DeviceStatus;
import cn.net.wanji.service.DataCopyService;
import cn.net.wanji.utils.HttpUtils;
import cn.net.wanji.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class DataCopyServiceImpl implements DataCopyService {

    @Resource
    ApplicationConfig applicationConfig;


    @Override
    @Async("doSomethingExecutor")
    public void dataReceive(JsonRoot jsonRoot) {
        // 主节点 向备用服务器同步
        if (!applicationConfig.getDataCopyIsMaster()) {
            return;
        }
        Map<String, String> mapParams = new HashMap<>();
        mapParams.put("jsonRoot", JSON.toJSONString(jsonRoot));
        String res = HttpUtils.sendPostRequest(applicationConfig.getDataCopySlavePath() + "receive/data", mapParams);
        log.info("dataReceive 数据同步: " + res);
    }

    @Override
    public void saveFile(List<File> files, Integer[] fileTypes, String recordId) {
        // 主节点 向备用服务器同步
        if (!applicationConfig.getDataCopyIsMaster()) {
            return;
        }

        Map<String, String> mapParams = new HashMap<>();
        mapParams.put("recordId", recordId);
        mapParams.put("fileTypes", StringUtils.arraysToString(fileTypes));
        String upload = HttpUtils.upload(applicationConfig.getDataCopySlavePath() + "receive/uploadFile", files, mapParams);
        log.info("saveFile 数据同步: " + upload);
    }

    @Override
    @Async("doSomethingExecutor")
    public void deviceInfoData(DeviceInfo deviceInfo) {
        // 主节点 向备用服务器同步
        if (!applicationConfig.getDataCopyIsMaster()) {
            return;
        }

        Map<String, String> mapParams = new HashMap<>();
        mapParams.put("jsonRoot", JSON.toJSONString(deviceInfo));
        String res = HttpUtils.sendPostRequest(applicationConfig.getDataCopySlavePath() + "receive/deviceInfoData", mapParams);
        log.info("deviceInfoData 数据同步: " + res);

    }

    @Override
    @Async("doSomethingExecutor")
    public void deviceStatusData(DeviceStatus deviceStatus) {
        // 主节点 向备用服务器同步
        if (!applicationConfig.getDataCopyIsMaster()) {
            return;
        }

        Map<String, String> mapParams = new HashMap<>();
        mapParams.put("jsonRoot", JSON.toJSONString(deviceStatus));
        String res = HttpUtils.sendPostRequest(applicationConfig.getDataCopySlavePath() + "receive/deviceStatusData", mapParams);
        log.info("deviceStatusData 数据同步: " + res);
    }
}
